package butines.game.state;

import butines.core.game.fsm.StateMachine;
import butines.core.math.Vector2f;
import butines.game.Steering;
import butines.game.Unit;

public class ChaseToEnemyState extends AbstractState {
	
	private static final ChaseToEnemyState instance = new ChaseToEnemyState();
	
	public static ChaseToEnemyState getInstance() {
		return instance;
	}

	@Override
	public void enter(Unit owner) {
		Vector2f target = owner.getEnemy().getPosition();
		Steering steering =  owner.getSteering();
		steering.getSeek().turnOn(target);
	}

	@Override
	public void leave(Unit owner) {
		Steering steering = owner.getSteering();
		steering.getSeek().turnOff();
	}

	@Override
	public void execute(Unit owner) {
		Unit enemy  = owner.getEnemy();
		StateMachine<Unit> stateMachine = owner.getStateMachine();
		
		if (enemy == null || enemy.isDead()) {
			owner.setEnemy(null);
			stateMachine.changeState(StayState.getInstance());
			return;
		}
		
		Vector2f target = owner.getEnemy().getPosition();
		Steering steering =  owner.getSteering();
		steering.getSeek().getTarget().set(target);

		if (owner.isNearToEnemy()) {
			owner.getStateMachine().revertToPreviousState();
			return;
		}
		
		owner.walk();
	}
		
}
